<template>

  <div v-loading="loading">
    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" style="margin-bottom: 15px">
        <span>{{ t('basicInfo') }}</span>
      </div>
      <el-descriptions border column="3" v-show="baseInfo">
        <el-descriptions-item v-for="(value, key) in baseInfo" :key="key" :label="translateKey(key)">
          {{ transformValue(key, value) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header" class="clearfix" style="margin-bottom: 5px">
        <span>{{ t('followHistory') }}</span>
      </div>
      <div v-if="data.history && data.history.length > 0">
        <el-table :data="data.history">
          <!-- recover_status -->
          <el-table-column prop="recover_status" :label="t('recoverStatus')">
            <template v-slot="{ row }">
              {{ recoverStatusOption[row.recover_status] }}
            </template>
          </el-table-column>
          <!-- order_id -->
          <el-table-column prop="order_id" :label="t('orderId')"></el-table-column>
          <!-- mission_id -->
          <el-table-column prop="mission_id" :label="t('missionId')">
            <template v-slot="{ row }">
              {{ missionIdOption[row.mission_id] }}
            </template>
          </el-table-column>
          <!-- follow_name -->
          <el-table-column prop="follow_name" :label="t('followName')"></el-table-column>
          <!-- follow_status -->
<!--          <el-table-column prop="follow_status" :label="t('followStatus')">
            <template v-slot="{ row }">
              {{ followStatusOption[row.follow_status] }}
            </template>
          </el-table-column>-->
          <!-- change_reason -->
          <el-table-column prop="change_reason" :label="t('changeReason')">
            <template v-slot="{ row }">
              {{ changeReasonOption[row.change_reason] }}
            </template>
          </el-table-column>
          <!-- create_time -->
          <el-table-column prop="create_time" :label="t('createTime')"></el-table-column>
          <!-- update_time -->
          <el-table-column prop="update_time" :label="t('updateTime')"></el-table-column>
          <!-- last_repay_will -->
          <el-table-column prop="last_repay_will" :label="t('lastRepayWill')">
            <template v-slot="{ row }">
              {{ lastRepayWillOption[row.last_repay_will] }}
            </template>
          </el-table-column>
          <!-- last_follow_result -->
          <el-table-column prop="last_follow_result" :label="t('lastFollowResult')">
            <template v-slot="{ row }">
              {{ lastFollowResultOption[row.last_follow_result] }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--  <el-table :data="data.history" style="width: 100%" >
          <el-table-column
            v-for="key in historyKeys"
            :key="key"
            :prop="key"
            :label="translateKey(key)"
            :formatter="key in historyValueMappings ? (row) => historyValueMappings[key][row[key]] : undefined"
          ></el-table-column>
        </el-table>-->
    </el-card>

    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header" class="clearfix" style="margin-bottom: 5px">
        <span>{{ t('contactInfo') }}</span>
      </div>
      <el-table :data="data.contact" style="width: 100%">
        <el-table-column
          v-for="key in contactKeys"
          :key="key"
          :prop="key"
          :label="translateKey(key)"
          :formatter="key in contactValueMappings ? (row) => contactValueMappings[key][row[key]] : undefined"
        ></el-table-column>
      </el-table>
    </el-card>

    <el-button v-show="data.id" type="primary" style="margin-top: 20px; margin-bottom: 30px;width: 120px"
               @click="editForm.dialogVisible = true">{{ t('update') }}
    </el-button>
  </div>
  <!-- 编辑弹窗 -->
  <el-dialog :label="t('tip')" v-model="editForm.dialogVisible" v-loading="editForm.loadingVisible">
    <el-form :model="editForm">
      <el-form-item :label="t('lastFollowResult')">
        <el-select v-model="editForm.last_follow_result" :placeholder="t('pleaseSelect')">
          <el-option
            v-for="(label, value) in lastFollowResultOption"
            :key="value"
            :label="label"
            :value="value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="t('lastRepayWill')">
        <el-select v-model="editForm.last_repay_will" :placeholder="t('pleaseSelect')">
          <el-option
            v-for="(label, value) in lastRepayWillOption"
            :key="value"
            :label="label"
            :value="value"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editForm.dialogVisible = false">{{ t('cancel') }}</el-button>
        <el-button type="primary" @click="handleConfirm">{{ t('submit') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import {
  ElCard,
  ElRow,
  ElCol,
  ElDescriptions,
  ElDescriptionsItem,
  ElTimeline,
  ElTimelineItem,
  ElTable,
  ElTableColumn,
  ElButton, ElMessage
} from 'element-plus'
import { useRoute } from 'vue-router'
import { doUpdateRecover, doGetRecoverDetailById } from '@/api/collect'
import {
  followStatusOption,
  lastFollowResultOption,
  lastRepayWillOption,
  missionIdOption,
  recoverStatusOption,
  repayStatusOption,
  historyValueMappings,
  contactValueMappings, changeReasonOption
} from '@/views/collectManage/reflect'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const route = useRoute()
// 假设这是从API获取的数据
const data = ref({
  id: '',
  history: [],
  contact: []
})
const id = ref('')
const loading = ref(false)
const contactKeys = ['name', 'mobile', 'contact_status', 'contact_type']

const baseInfo = computed(() => {
  return Object.fromEntries(Object.entries(data.value).filter(([key]) => !['history', 'contact'].includes(key)))
})

onMounted(() => {
  const recoverId = route.query.id
  id.value = recoverId
  _loadDetailById()
})

const _loadDetailById = () => {
  loading.value = true
  doGetRecoverDetailById(id.value).then((res) => {
    if (res != null && res.id) {
      data.value = res
    }
  }).catch((err) => {
    console.log('err:', err)
  }).finally(() => {
    loading.value = false
  })
}

// 编辑表单的数据模型
const editForm = reactive({
  loadingVisible: false,
  dialogVisible: false,
  last_follow_result: null,
  last_repay_will: null
})

// 翻译字段名称
const translateKey = (key) => {
  const translations = {
    id: t('id'),
    order_id: t('orderId'),
    overdue_day: t('overdueDay'),
    period_no: t('periodCount'),
    loan_term: t('deadline'),
    product_id: t('productId'),
    name: t('name'),
    mobile: t('phone'),
    mission_id: t('missionId'),
    follow_id: t('followId'),
    follow_name: t('followName'),
    follow_time: t('followTime'),
    recover_status: t('recoverStatus'),
    last_follow_result: t('lastFollowResult'),
    last_repay_will: t('lastRepayWill'),
    last_op_time: t('lastOpTime'),
    repay_status: t('repayStatus'),
    follow_status: t('followStatus'),
    create_time: t('createTime'),
    update_time: t('updateTime'),
    change_reason: t('changeReason'),
    contact_status: t('contactStatus'),
    contact_type: t('contactType')
  }
  return translations[key] || key
}

// 转换特定字段的值为中文描述
const transformValue = (key, value) => {
  const mappings = {
    last_follow_result: lastFollowResultOption,
    last_repay_will: lastRepayWillOption,
    repay_status: repayStatusOption,
    mission_id: missionIdOption,
    follow_status: followStatusOption,
    recover_status: recoverStatusOption
  }
  // 如果字段对应有映射，则返回映射的值，否则返回原始值
  return mappings[key] && mappings[key][value] !== undefined
    ? mappings[key][value]
    : value
}

const handleConfirm = () => {
  if (!editForm.last_follow_result) {
    ElMessage.error(t('selectLastFollowReason'))
    return
  }
  if (!editForm.last_repay_will) {
    ElMessage.error(t('selectLastRepayWill'))
    return
  }
  editForm.loadingVisible = true
  doUpdateRecover(
    id.value,
    editForm.last_follow_result,
    editForm.last_repay_will
  ).then(() => {
    ElMessage.success(t('updateSuccess'))
    editForm.dialogVisible = false
    _loadDetailById()
  }).catch(() => {
    ElMessage.error(t('updateFail'))
  }).finally(() => {
    editForm.loadingVisible = false
  })
}
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
  margin-right: 20px;
}
</style>
